<template>
  <el-dialog v-model="visible" :title="title" width="600px" destroy-on-close @close="emit('close')">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="FUsername">
        <el-input v-model="formData.FUsername" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="是否激活" prop="FIsActive">
        <el-switch v-model="formData.FIsActive" active-text="激活" inactive-text="禁用" />
      </el-form-item>

      <el-form-item label="所属部门" prop="departmentId">
        <el-cascader
          v-model="formData.departmentId"
          :options="flattenedDepartments"
          :props="cascaderProps"
          :show-all-levels="false"
          clearable
          filterable
          multiple
          style="width: 100%"
          placeholder="请选择部门"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getDepartmentTreeApi } from "@/api/modules/department";
import { Department } from "@/api/interface/department";
import { createUserApi, updateUserApi } from "@/api/modules/admin";
import { Admin } from "@/api/interface/admin";

const emit = defineEmits(["refresh", "close"]);

const visible = ref(false);
const formRef = ref<FormInstance>();
const title = ref("新增用户");
const departmentTree = ref<Department.DepartmentItem[]>([]);

const formData = reactive({
  FUserId: "",
  FUsername: "",
  FIsActive: true,
  departmentId: ""
});

const rules = reactive<FormRules>({
  FUsername: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  departmentId: [{ required: true, message: "请至少选择一个部门", trigger: "change" }]
});

// 级联选择器配置
const cascaderProps = {
  value: "FId",
  label: "FName",
  children: "children",
  emitPath: false,
  checkStrictly: true
};

// 扁平化部门数据用于显示
const flattenedDepartments = computed(() => {
  return departmentTree.value;
});

// 加载部门树
const loadDepartments = async () => {
  const { data } = await getDepartmentTreeApi();
  departmentTree.value = data;
};

// 打开弹窗
const open = (row?: Admin.UserItem) => {
  title.value = row?.FUserId ? "编辑用户" : "新增用户";
  if (row?.FUserId) {
    Object.assign(formData, {
      FUserId: row.FUserId,
      FUsername: row.FUsername,
      FIsActive: row.FIsActive,
      departmentId: row.department?.FId
    });
  } else {
    resetForm();
  }
  console.log(formData);

  visible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.FUserId = "";
  formData.FUsername = "";
  formData.FIsActive = true;
  formData.departmentId = "";
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    const params = {
      ...formData,
      departmentId: formData.departmentId
    };

    if (formData.FUserId) {
      await updateUserApi(params);
      ElMessage.success("用户更新成功");
    } else {
      await createUserApi(params);
      ElMessage.success("用户创建成功");
    }

    visible.value = false;
    emit("refresh");
  } catch (error) {
    console.error("表单提交失败:", error);
  }
};

// 初始化加载部门数据
onMounted(() => {
  loadDepartments();
});

defineExpose({ open });
</script>
